<template>
  <div class="user-management">
    <div class="header">
      <div class="title">用户管理</div>
      <div class="toolbar">
        <el-input 
          v-model="searchQuery" 
          placeholder="搜索姓名/工号"
          clearable
          style="width: 200px; margin-right: 10px"
        >
          <template #append>
            <el-button icon="Search" @click="handleSearch" />
          </template>
        </el-input>
        <el-button type="primary" @click="openAddDialog">
          <el-icon><Plus /></el-icon>
          新增用户
        </el-button>
      </div>
    </div>

    <el-row :gutter="20" class="main-content">
      <el-col :span="6">
        <el-card class="dept-tree" shadow="never">
          <template #header>
            <div class="card-header">
              <span>部门结构</span>
            </div>
          </template>
          <el-tree
            :data="departments"
            :props="treeProps"
            @node-click="handleNodeClick"
            default-expand-all
          />
        </el-card>
      </el-col>
      <el-col :span="18">
        <el-card shadow="never">
          <el-table :data="pageUsers" border stripe v-loading="loading">
            <el-table-column label="工号" prop="empId" width="120" align="center" />
            <el-table-column label="姓名" prop="name" width="120" align="center" />
            <el-table-column label="性别" width="80" align="center">
              <template #default="{ row }">
                <span>{{ row.gender === 'male' ? '男' : '女' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="部门" prop="department" align="center" />
            <el-table-column label="角色" width="120" align="center">
              <template #default="{ row }">
                <el-tag>{{ row.role }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="手机号" prop="phone" width="150" align="center" />
            <el-table-column label="操作" width="150" align="center">
              <template #default="{ row }">
                <el-button link type="primary" @click="openEditDialog(row)">编辑</el-button>
                <el-button link type="danger" @click="handleDelete(row.empId)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :total="total"
              :page-sizes="[10, 20, 50]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form :model="form" label-width="80px" :rules="rules" ref="formRef">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="form.gender">
            <el-radio label="male">男</el-radio>
            <el-radio label="female">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="部门" prop="department">
          <el-cascader
            v-model="form.department"
            :options="departments"
            :props="cascaderProps"
            placeholder="请选择部门"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="form.role" placeholder="请选择角色" style="width: 100%">
            <el-option
              v-for="item in roleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Search, Plus } from '@element-plus/icons-vue'

// 模拟数据
const departments = ref([
  {
    id: 1,
    label: '总公司',
    children: [
      { id: 11, label: '人事部' },
      { id: 12, label: '财务部' },
      { id: 13, label: '技术部' }
    ]
  }
])

const mockUsers = ref([
  {
    empId: '1001',
    name: '张三',
    gender: 'male',
    department: '技术部',
    role: '管理员',
    phone: '13800138000'
  }
])

// 响应式数据
const searchQuery = ref('')
const loading = ref(false)
const dialogVisible = ref(false)
const form = ref({})
const formRef = ref(null)
const currentDept = ref('')

// 配置项
const treeProps = { label: 'label', children: 'children' }
const cascaderProps = { value: 'label', checkStrictly: true }
const roleOptions = [
  { value: 'admin', label: '管理员' },
  { value: 'staff', label: '普通员工' },
  { value: 'finance', label: '财务人员' }
]

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  department: [{ required: true, message: '请选择部门', trigger: 'change' }],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ]
}

// 计算属性
const filteredUsers = computed(() => {
  return mockUsers.value.filter(user => {
    const matchSearch = user.name.includes(searchQuery.value) || 
      user.empId.includes(searchQuery.value)
    const matchDept = currentDept.value ? 
      user.department === currentDept.value : true
    return matchSearch && matchDept
  })
})

const dialogTitle = computed(() => form.value.empId ? '编辑用户' : '新增用户')

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = computed(() => filteredUsers.value.length)

const pageUsers = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredUsers.value.slice(start, end)
})

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}

// 方法
const openAddDialog = () => {
  form.value = {
    empId: '',
    name: '',
    gender: '',
    department: '',
    role: '',
    phone: ''
  }
  dialogVisible.value = true
}

const openEditDialog = (row) => {
  form.value = { ...row }
  dialogVisible.value = true
}

const handleSubmit = async () => {
  const valid = await formRef.value.validate()
  if (!valid) return

  if (form.value.empId) {
    // 更新逻辑
    const index = mockUsers.value.findIndex(u => u.empId === form.value.empId)
    mockUsers.value.splice(index, 1, form.value)
  } else {
    // 新增逻辑
    form.value.empId = `U${mockUsers.value.length + 1000}`
    mockUsers.value.push(form.value)
  }
  dialogVisible.value = false
}

const handleDelete = (empId) => {
  const index = mockUsers.value.findIndex(u => u.empId === empId)
  mockUsers.value.splice(index, 1)
}

const handleNodeClick = (node) => {
  currentDept.value = node.label
}

const handleSearch = () => {
  // 实际应调用API
}
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title {
  font-size: 20px;
  font-weight: bold;
}

.toolbar {
  display: flex;
  justify-content: flex-end;
}

.main-content {
  min-height: 500px;
}

.dept-tree {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>